package com.zhida.common.utils;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.concurrent.CompletableFuture;

/**
 * Create by zhh 2024/7/30 15:56
 */
public class CodeUtil {

    private static final String ACCESS_KEY_ID = "LTAI5tHT5JFb1U1qh1CMMqWb";
    private static final String ACCESS_KEY_SECRET = "DCNRwOPscnDLwplwlXULxJ4IDs04mV";
    private static final String templateCode = "SMS_470905062";
    private static final String signName = "职达";

    public static String generateCode(String phoneNumber) throws Exception {

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(ACCESS_KEY_ID)
                .accessKeySecret(ACCESS_KEY_SECRET)
                .build());
        AsyncClient client = AsyncClient.builder()
                .region("cn-chengdu") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();

        int code = createCode();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phoneNumber)
                .signName(signName)
                .templateCode(templateCode)
                .templateParam("{\"code\":\""+ code +"\"}")
                .build();

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        client.close();
        return String.valueOf(code);
    }

    public static int createCode() {
//        创建一个六位数的验证码
        return (int) ((Math.random() * 9 + 1) * 100000);
    }
}
